作者:518094haha | 来源:互联网 | 2023-05-19 15:59
ImdevelopingaWebapplicationandwanttodisplayafigureanditslegendindifferentlocations
I'm developing a Web application and want to display a figure and its legend in different locations on the page. Which means I need to save the legend as a separate png file. Is this possible in Matplotlib in a more or less straightforward way?
我正在开发一个Web应用程序,并希望在页面上的不同位置显示一个图形及其图例。这意味着我需要将图例保存为单独的png文件。这在Matplotlib中是否可能以一种或多或少的直接方式实现?
5 个解决方案
6
This calculates the size of the legend automatically. If mode == 1
, the code is similar to Steve Tjoa's answer, while mode == 2
is similar Andre Holzner's answer.
这会自动计算图例的大小。如果mode == 1,代码类似于Steve Tjoa的答案,而mode == 2则类似于Andre Holzner的答案。
The loc
parameter must be set to 'center'
to make it work (but I do not know why this is necessary).
loc参数必须设置为'center'才能使其工作(但我不知道为什么这是必要的)。
mode = 1
#mode = 2
import pylab
fig = pylab.figure()
if mode == 1:
lines = fig.gca().plot(range(10), pylab.randn(10), range(10), pylab.randn(10))
legend_fig = pylab.figure(figsize=(3,2))
legend = legend_fig.legend(lines, ('one', 'two'), 'center')
if mode == 2:
fig.gca().plot(range(10), pylab.randn(10), range(10), pylab.randn(10), label='asd')
legend_fig = pylab.figure()
legend = pylab.figlegend(*fig.gca().get_legend_handles_labels(), loc = 'center')
legend.get_frame().set_color('0.70')
legend_fig.canvas.draw()
legend_fig.savefig('legend_cropped.png',
bbox_inches=legend.get_window_extent().transformed(legend_fig.dpi_scale_trans.inverted()))
legend_fig.savefig('legend_original.png')
Original (uncropped) legend:
原始(未剪切)传奇:
如果由于某种原因您只想隐藏轴标签,您可以使用:
ax.xaxis.set_visible(False)
ax.yaxis.set_visible(False)
or if, for some weirder reason, you want to hide the axes frame but not the axes labels you can use:
或者,如果出于某种奇怪的原因,您想要隐藏轴框架而不是轴标签,您可以使用:
ax.set_frame_on(False)
ps: this answer has been adapted from my answer to a duplicate question
ps:这个答案改编自我对一个重复问题的回答